package cn.com.dhc.danlu.activity.base;

import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.widget.adapter.BaseFragmentPagerAdapter;

/**
 * User: Geek_Soledad(wuhaiyang@danlu.com)
 * Date: 2016-09-22
 * Time: 18:10
 * Description: 通用tabViewPager Fragment
 */
public abstract class DanluTabFragmentActivity extends DanluBaseActivity {
    protected ViewPager mViewPager;
    protected TabLayout mTabLayout;
    protected BaseFragmentPagerAdapter adapter;

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initView();
        setComponentAttr();
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        initView();
        setComponentAttr();
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        initView();
        setComponentAttr();
    }

    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);
    }

    private void setComponentAttr() {
        adapter = new BaseFragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            protected String[] initTitles() {
                return createTitles();
            }

            @Override
            public Fragment getItem(int position) {
                return getFragmentByPos(position);
            }
        };
        mViewPager.setAdapter(adapter);
        mTabLayout.setupWithViewPager(mViewPager);
        setTabAttr();
    }

    protected abstract String[] createTitles();

    protected abstract Fragment getFragmentByPos(int position);

    protected void setTabAttr() {
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
    }

    protected void updateTitle(int index, @NonNull String updateContent) {
        int tabCount = mTabLayout.getTabCount();
        if (index >= tabCount) {
            throw new RuntimeException("can not beyond tabcount");
        }
        mTabLayout.getTabAt(index).setText(updateContent);
    }
}